package delete;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import db.DBManager;

public class UserDeleteServlet extends HttpServlet 
{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		perform(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		perform(req, resp);
	}
	
	protected void perform(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		req.setCharacterEncoding("UTF-8");
		StringBuffer msg = new StringBuffer();
		
		//ユーザーIDを取得
		String strId = req.getParameter("id");
		int id = 0;		//初期化
		//入力チェック
		if(strId == null || strId.length() == 0)
		{
			msg.append("ユーザーIDを入力してください\n");
		}
		else
		{
			try
			{
				id = Integer.parseInt(strId);
			}
			catch(NumberFormatException e)
			{
				msg.append("半角英数で入力してください\n");
				e.printStackTrace();
			}
		}
		
		try
		{
			//データベースに接続
			Connection con = DBManager.getConnection();
			//IDからユーザーを検索
			String sql = "select * from UserAccount where id = ?";
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setInt(1, id);
			ResultSet rs = ps.executeQuery();
			//検索結果
			Delete d = new Delete();
			if(rs.next())	//true
			{
				d.setId(rs.getInt("id"));
				d.setName(rs.getString("name"));
			}
			else if(msg.length() == 0)
			{
				msg.append("該当ユーザーがいません\n");
			}
			rs.close();
			ps.close();
			
			
			RequestDispatcher dispatcher = null;
			//エラーがなければ確認画面へ
			if(msg.length() == 0)
			{
				req.setAttribute("delete", d);
				dispatcher = req.getRequestDispatcher("/delete/UserDelete.jsp");
				dispatcher.forward(req, resp);
			}
			else
			{
				req.setAttribute("msg", msg.toString());
				dispatcher =req.getRequestDispatcher("/delete/index.jsp");
				dispatcher.forward(req, resp);
			}
			
			con.close();
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
	}
}
